package tech.yozo.bamboo.model;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TranslateEngine {
    /**
     * 翻译
     * @param text 待翻译文本
     */
    public static String doTranslate(String text) {
        String result;
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), "{\n" +
                "  \"model\": \"qwen-mt-turbo\",\n" +
                "  \"messages\": [\n" +
                "    {\n" +
                "      \"role\": \"user\",\n" +
                "      \"content\": \"" + text + "\"\n" +
                "    }\n" +
                "  ],\n" +
                "  \"translation_options\": {\n" +
                "    \"source_lang\": \"English\",\n" +
                "    \"target_lang\": \"Chinese\"\n" +
                "  }\n" +
                "}");
        Request request = new Request.Builder()
                .url("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions")
                .addHeader("Authorization", "Bearer sk-aa6571594f8845409c7da77d0b1e71c1")
                .post(body)
                .build();
        //准备好请求的Call对象
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            assert response.body() != null;
            JSONObject object = new JSONObject(response.body().string());
            response.close();

            result = object
                    .getJSONArray("choices")
                    .getJSONObject(0)
                    .getJSONObject("message")
                    .getString("content");
            Log.i("Translation", result);
        } catch (JSONException | IOException e) {
            result = "翻译失败";
        }
        return result;
    }
}
